package com.android.powerbankpad.network.retrofit;


import com.lzy.okgo.https.HttpsUtils;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.ws.universal.tools.network.HttpLogInterceptor;

import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class RetrofitServiceManager {


    private static final String BASE_URL = "http://app.w-dian.cn/";

    private static RetrofitServiceManager instance;
    private Retrofit retrofit;

    private RetrofitServiceManager() {

        OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();


        // 添加一个日志拦截器，用于调试目的
        HttpLogInterceptor loggingInterceptor = new HttpLogInterceptor("下载音频");
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
        loggingInterceptor.setColorLevel(Level.INFO);
        clientBuilder.addInterceptor(loggingInterceptor);

        // 设置连接超时、写操作超时和读操作超时
        clientBuilder.connectTimeout(60, TimeUnit.SECONDS);
        clientBuilder.writeTimeout(60, TimeUnit.SECONDS);
        clientBuilder.readTimeout(60, TimeUnit.SECONDS);


        //方法一：信任所有证书,不安全有风险
        HttpsUtils.SSLParams sslParams1 = HttpsUtils.getSslSocketFactory();

        // 创建 OkHttpClient
        OkHttpClient client = clientBuilder.sslSocketFactory(sslParams1.sSLSocketFactory, sslParams1.trustManager).build();
        // 创建 Retrofit 实例
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .addConverterFactory(ScalarsConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())

                .build();
    }

    public static RetrofitServiceManager getInstance() {
        if (instance == null) {
            synchronized (RetrofitServiceManager.class) {
                if (instance == null) {
                    instance = new RetrofitServiceManager();
                }
            }
        }
        return instance;
    }

    public <T> T createService(Class<T> serviceClass) {
        return retrofit.create(serviceClass);
    }


}

